package com.zlq.cn.util.des;

import com.alibaba.fastjson.JSONObject;
import com.zlq.cn.util.des.hash.HrHex;
import com.zlq.cn.util.des.security.KFuPayDistAlgorithms;
import com.zlq.cn.util.des.security.KFuPayTriDES;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class KFuPayDecryptUtil {

	private static String KEY = "md5key";

	/**
	 * 加密
	 * 
	 * @param s
	 *            需要加密的数据
	 * @return [0] 随机码 [1] 加密后的数据
	 */
	public static String[] encrypt(String random, String s, String key) {
		String[] as = null;
		try {
			String transKey = KFuPayDistAlgorithms.getTransKey(key, random);

			byte[] bytePasswd = KFuPayTriDES.encryptWithPKCS5Padding(s, transKey);
			String encryS = HrHex.encode(bytePasswd);
			as = new String[2];
			as[0] = random;
			as[1] = encryS;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return as;
	}

	/**
	 * 解密
	 * 
	 * @param random
	 *            随机码
	 * @param p
	 *            加密的数据
	 * @return 解密后的数据
	 */
	public static String decrypt(String random, String p, String key) {
		String d = null;
		try {
			String transKey = KFuPayDistAlgorithms.getTransKey(key, random);

			byte[] encoded = HrHex.decode(p);
			byte[] decryptPassword = KFuPayTriDES.decryptWithPKCS5Padding(encoded, transKey);
			d = new String(decryptPassword, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return d;
	}


	public static String orderedEndKey(JSONObject json, String extraKey){
		List<String> keys = new ArrayList(json.keySet());

		StringBuffer sbuf = new StringBuffer("");
		String [] arrayToSort = keys.toArray(new String[keys.size()]);
		Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);

		for (int i = 0; i < arrayToSort.length; i++) {
			String key = arrayToSort[i];
			Object value = json.get(key);
			if(value!=null && !"".equals(value) && !"null".equals(value)){
				sbuf.append(key).append("=").append(value).append("&");
			}
		}
		String result = sbuf.toString();
		if(StringUtils.isNotBlank(extraKey)){
			sbuf.append(KEY).append("=").append(extraKey);
			result = sbuf.toString();
		}else{
			result = result.substring(0, result.length()-1);
		}
		return result;
	}


}
